import axios from '@ohos/axios'
import { promptAction } from '@kit.ArkUI';
import type {AnyObject} from '../../models/HttpModel'

//参考文档：https://ohpm.openharmony.cn/#/cn/detail/@ohos%2Faxios
const request =axios.create({
  //如果写localhost在模拟器中可能无法使用，写ip注意ip可能会变动
  baseURL:'http://192.168.43.30:4523/m1/2812017-1021254-default'
})

request.interceptors.request.use(
  (config)=>{
    console.log('[axios request config]:'+JSON.stringify(config))




    //TODO:后期配置token
    return config;
  }
)
//响应拦截：处理正常和错误的响应
request.interceptors.response.use(
  (response)=>{
    console.log('[axios response]:'+JSON.stringify(response))
    if(response.data.flag){
        return response.data.data;
    }else{
      console.log('[axios responseMessage]:'+response.data.message)
      //错误提示
      promptAction.showToast( {message:response.data.message} )
      return Promise.reject(response.data.message);
    }
  },
  (error)=>{
    //错误提示
    console.log('[axios error]:'+error.message)
    promptAction.showToast({message:error.message})
    return Promise.reject(error.message)
  }
)

export default class Http{
  get<T>(url:string,params?:AnyObject){
    return request.get<any,T>(url,{params})
  }
  post<T>(url:string,data?:AnyObject){
    return request.post<any,T>(url,data)
  }
  put<T>(url:string,data?:AnyObject){
    return request.put<any,T>(url,data)
  }
  delete<T>(url:string,params?:AnyObject){
    return request.delete<any,T>(url,{params})
  }



}
